﻿#coding=utf-8
import os,time,urllib
import md5,random,sys
from phonesite import settings
from forum.models import *
from django.core.exceptions import ObjectDoesNotExist
from django.http import HttpResponse
from django.http import HttpRequest
from django.http import HttpResponseRedirect

from django.template import loader
from django.shortcuts import render_to_response
from django.db.models import Q


from django.views.generic import list_detail
from django.shortcuts import get_object_or_404
from django.core.mail import send_mail, BadHeaderError

from django.core.cache import cache  


#show register page
def show_register_page(request):

    if request.method == 'POST':
       username = request.POST.get('username', '')
       pwd = request.POST.get('password', '')
       returl = request.POST.get('returl', '')
       #check post param
       if username == '' or pwd == '':
           error = '错误'
           return HttpResponse(loader.render_to_string('forum/register.wml',{'error':error,'returl':returl}),"text/vnd.wap.wml")
       #create new user and store into db
       users = User.objects.filter(user_name=username)
       if users:
           error = '用户名已存在'
	   return HttpResponse(loader.render_to_string('forum/register.wml',{'error':error,'returl':returl}),"text/vnd.wap.wml")
       _uid = md5.new(str(random.randint(0, sys.maxint - 1)) + str(random.randint(0, sys.maxint - 1)) + settings.SECRET_KEY).hexdigest()
       user = User(user_name=username,password=pwd,uid=_uid,login_count=1,money=10,level='玩机菜鸟',topic_num_per_page=10)
       user.signed_name = '无'
       user.nick_name = username
       #user.board_master.id = 1
       user.save()
       #redirect to userinfo page
       if returl == '':
	   #redirect to redirect_url
	   redirect_url = '/forum/user/?userid=' + str(user.id) + '&uid=' + str(_uid)
       #redirect to returl
       else:
	   if returl.find('?') != -1:
		redirect_url = returl + '&uid=' + _uid
	   else:
		redirect_url = returl + '?uid=' + _uid
       return HttpResponseRedirect(redirect_url)	
    else:
       returl = request.GET.get('returl', '')
       return HttpResponse(loader.render_to_string('forum/register.wml',{'returl':returl}),"text/vnd.wap.wml")

#show userinfo page,any user can look other users' info page,include no login user
def show_userinfo_page(request):

    _uid = request.GET.get('uid', '')
    _userid = request.GET.get('userid', '')
    try:
	    user = User.objects.get(id=_userid)
    except ObjectDoesNotExist:
	    #there isn't this user, show a error page
	    return HttpResponse(loader.render_to_string('forum/nouser.wml',{'uid':_uid}),"text/vnd.wap.wml")
    #there is this user,show his userinfo page
    return HttpResponse(loader.render_to_string('forum/user.wml',{'user':user,'uid':_uid}),"text/vnd.wap.wml")
		
#show index page
def show_index_page(request):

    _uid = request.GET.get('uid', '')
    users = User.objects.filter(uid=_uid)
    board_types = BoardType.objects.all()
    board_all = []
    for _board_type in board_types:
        boards = Board.objects.filter(board_type=_board_type)
        board_all.append(boards)
    
    if users:
        user = users[0]
        return HttpResponse(loader.render_to_string('forum/index.wml',{'board_all':board_all,'user':user,'uid':_uid}),"text/vnd.wap.wml")
    else:
        return HttpResponse(loader.render_to_string('forum/index.wml',{'board_all':board_all,'uid':_uid}),"text/vnd.wap.wml")

#show board page
def show_board_page(request):

    _uid = request.GET.get('uid', '')
    _board_id = request.GET.get('bid', '')
    page = request.GET.get('page', '1')
    try:
	    board = Board.objects.get(id=_board_id)
    except ObjectDoesNotExist:
	    #there isn't this user, show a error page
	    return HttpResponse(loader.render_to_string('forum/noboard.wml',{'uid':_uid}),"text/vnd.wap.wml")
    users = User.objects.filter(uid=_uid)
    topics = Topic.objects.filter(board=_board_id)
    
    #分页显示
    count = topics.count()
    page_count = 0
    page_int = int(page)
    yushu = count % 10
    if yushu == 0:
      page_count = count / 10
    else:
      page_count = count / 10 + 1
    
    if count == 0:
        page_count = 1
    if page_int*10 <= count:
        topics = topics[(page_int-1)*10:page_int*10]
    else:
        topics = topics[(page_int-1)*10:count]
    
    cur_page = page_int
    has_prev = False
    has_next = False
    prev_page = 0
    next_page = 0
    if cur_page == 1:
       has_prev = False
    else:
       has_prev = True
       prev_page = cur_page-1
    if cur_page == page_count:
       has_next = False
    else:
       has_next = True
       next_page = cur_page+1
    count_list = range(1,page_count+1)

    if users:
        user = users[0]
        return HttpResponse(loader.render_to_string('forum/board.wml',{'user':user,'uid':_uid,'page':page_int,'count':count,'page_count':page_count,'has_prev':has_prev,'has_next':has_next,'prev_page':prev_page,'next_page':next_page,'topics':topics,'board':board}),"text/vnd.wap.wml")
    else:
        return HttpResponse(loader.render_to_string('forum/board.wml',{'uid':_uid,'page':page_int,'count':count,'page_count':page_count,'has_prev':has_prev,'has_next':has_next,'prev_page':prev_page,'next_page':next_page,'topics':topics,'board':board}),"text/vnd.wap.wml")
    
#show login page
def show_login_page(request):

    if request.method == 'POST':
       username = request.POST.get('username', '')
       pwd = request.POST.get('password', '')
       returl = request.POST.get('returl', '')
       #check post param
       if username == '':
           error = '请输入用户名'
           return HttpResponse(loader.render_to_string('forum/login.wml',{'error':error,'returl':returl}),"text/vnd.wap.wml")
       if pwd == '':
           error = '请输入密码'
           return HttpResponse(loader.render_to_string('forum/login.wml',{'error':error,'returl':returl}),"text/vnd.wap.wml")
       
       #check whether or not this user is exist

       users = User.objects.filter(user_name=username)
       if users:
           user = users[0]
	   if user.password != pwd:
	       error = '密码不正确'
               return HttpResponse(loader.render_to_string('forum/login.wml',{'error':error,'returl':returl}),"text/vnd.wap.wml")
	   _uid = user.uid
           #redirect to userinfo page
           if returl == '':
	       #redirect to redirect_url
	       redirect_url = '/forum/?uid=' + str(_uid)
           #redirect to returl
           else:
	       if returl.find('?') != -1:
		   redirect_url = returl + '&uid=' + _uid
	       else:
		   redirect_url = returl + '?uid=' + _uid
           return HttpResponseRedirect(redirect_url)
       else:
           error = '该用户不存在'
           return HttpResponse(loader.render_to_string('forum/login.wml',{'error':error,'returl':returl}),"text/vnd.wap.wml")

    else:
       returl = request.GET.get('returl', '')
       return HttpResponse(loader.render_to_string('forum/login.wml',{'returl':returl}),"text/vnd.wap.wml")

#show topic page
def show_topic_page(request):

    _uid = request.GET.get('uid', '')
    _topicid = request.GET.get('topicid', '')
    try:
	    topic = Topic.objects.get(id=_topicid)
    except ObjectDoesNotExist:
	    #there isn't this user, show a error page
	    return HttpResponse(loader.render_to_string('forum/notopic.wml',{'uid':_uid}),"text/vnd.wap.wml")
    #user_id = topic.author.id
    #user = User.objects.get(id=user_id)
    return HttpResponse(loader.render_to_string('forum/topic.wml',{'topic':topic,'uid':_uid}),"text/vnd.wap.wml")


#show map page
def show_map_page(request):
    if request.method == 'POST':
        _lat = request.POST.get('lat', '90')
        _lon = request.POST.get('lon', '90')
        
        
        pic_name = _lat + ',' + _lon
        pic_path = "E://web_20080316//web//phonesite//media//ditu//" + pic_name + '.jpg'
        show_url = 'ditu/' + pic_name + '.png'
        if os.path.exists(pic_path):
            return HttpResponse(loader.render_to_string('forum/map.wml',{'url':show_url}),"text/vnd.wap.wml")
        
        url1 = "http://maps.google.com/staticmap?center=%s,%s" % (_lat,_lon)
        url2 = "&zoom=14&size=512x512&maptype=mobile&format=jpg"
        #url3 = "&markers=40.702147,-74.015794,blues%7C40.711614,-74.012318,greeng%7C40.718217,-"
        url4 = "&key=ABQIAAAA5zZGVpsHBvfJshGDS2xMJRQkrQqP-hmWhyp001jd86W-8ymwxxQP3InJEJAJLoSkz0BkJzPe2z5vDQ"
        url = url1 + url2 + url4
        f = urllib.urlopen(url)
        data = f.read()
        f.close()
        f = open(pic_path,'wb')
        f.write(data)
        f.close()
        return HttpResponse(loader.render_to_string('forum/map.wml',{'url':show_url}),"text/vnd.wap.wml")
    else:
        return HttpResponse(loader.render_to_string('forum/map.wml',{'url':''}),"text/vnd.wap.wml")
    